<template>
  <div class="common-page page-stats-order-government" v-loading.fullscreen="loading">
    <div class="common-page__head">
      <!-- <comp-paths class="route" :paths="['/stats', $route.fullPath]"></comp-paths> -->
      <div class="title">
        <div class="text">{{ $options.title }}</div>
        <el-date-picker type="date" v-model="startTime" size="small" style="margin-right: 12px; width: 200px"
                        format="起始yyyy年M月d日" value-format="timestamp" placeholder="起始日期" :readonly="loading"
                        @change="search()"></el-date-picker>
        <el-date-picker type="date" v-model="endTime" size="small" style="margin-right: 12px; width: 200px"
                        format="截止yyyy年M月d日" value-format="timestamp" placeholder="截止日期" :readonly="loading"
                        @change="search()"></el-date-picker>
        <el-select size="small" style="margin-right: 12px; width: 200px" v-model="orderType" @change="handleOrderChange">
          <el-option label="办结率" :value="'over'"></el-option>
          <el-option label="数量" :value="'count'"></el-option>
        </el-select>
        <el-button type="plain" size="small" icon="el-icon-top" @click="setDept()" v-if="deptId">
          返回上一级
        </el-button>
        <el-button
          style="width: 100px;  float: right"
          type="primary"
          size="small"
          @click="exportExcel"
        >导出Excel</el-button
        >
<!--        <el-button type="primary" size="small" icon="el-icon-download" @click="exportStats()">导出</el-button>-->
      </div>
    </div>
    <div id="exportTable-government-belong" class="common-page__body page-stats-order-government__body">
      <table id="exportTable-government" style="width: 40vw">
        <thead>
        <tr>
          <th >排名</th>
          <th v-if="!areaList">自治区级部门</th>
          <th v-else>区域</th>
          <th >事项总数</th>
          <th >办结数</th>
          <th >办结率</th>
        </tr>
        </thead>
        <tbody>
        <tr class="row" v-for="(government, index) in governmentList" :key="index">
          <td>{{ index + 1 }}</td>

          <td @click="setDept(government)"><span class="link">{{government.name }}</span></td>
          <td>{{ government.stats.ordersTotal }}</td>
          <td>{{ government.stats.ordersFinishedTotal }}</td>
          <td>{{ government.stats.ordersFinishedPercent }}</td>
        </tr>
        <tr v-for="(government, index) in areaList" :key="index">
          <td>{{ index + 1 }}</td>

          <td>{{government.name }}</td>
          <td>{{ government.stats.ordersTotal }}</td>
          <td>{{ government.stats.ordersFinishedTotal }}</td>
          <td>{{ government.stats.ordersFinishedPercent }}</td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import mixin from "../mixin";
import {string, int} from "../util";
import XLSX from "xlsx";

export default {
  name: "page-stats-order-government-belong",
  title: "办结率排名-自治区级及市区县职能部门",
  nodes: ["/menu/stats"],
  childs: [],
  mixins: [mixin],
  data: () => ({
    loading: false,
    startTime: null,
    endTime: null,
    orderType: 'over', // over:办结率  count:数量
    governmentList: [],
    areaList: [],
    deptId: null,
  }),
  methods: {
    setDept(government){
      this.deptId = government?.id
      this.search(true)
    },
    search(clean) {
      if (this.loading) return;
      if (clean) this.governmentList = [];
      let startTime = this.startTime;
      let endTime = this.endTime;
      this.loading = true;
      if(!this.deptId){
        this.plugins.user.getStatsOrderGovernmentBelong({startTime, endTime}).then((res) => {
          console.log(res);
          this.loading = false;
          if (res.code === 0) {
            this.handleFormatData(res.data)
          } else {
            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
          }
        });
      }else{
        const deptId = this.deptId
        this.plugins.user.getStatsOrderGovernmentBelongArea({deptId,startTime, endTime}).then((res) => {
          console.log(res);
          this.loading = false;
          if (res.code === 0) {
            this.handleFormatData(res.data)
          } else {
            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
          }
        });
      }

    },
    handleFormatData(dataList) {
      let list = dataList.map((data) => ({
        id: string(data.deptId || data.areaId),
        name: string(data.name),
        cityId: string(data.cityId),
        countyId: string(data.areaId),
        stats: {
          ordersTotal: int(data.countAll),
          ordersFinishedTotal: int(data.countStatus_5),
          ordersFinishedPercent: int(int(data.countStatus_5) / int(data.countAll), 4) / 100,
        },
      }));
      this.governmentList = this.deptId?[]:list.filter((data) => {
        return data
      })
      this.areaList = (!this.deptId)?[]:list.filter((data) => {
        return data
      })

      this.orderDataList(this.governmentList)
      this.orderDataList(this.areaList)
    },
    handleOrderChange(){
      this.orderDataList(this.governmentList)
      this.orderDataList(this.areaList)
    },
    orderDataList(dataList){
      dataList.sort((a, b) => {
        let a1 = a.stats.ordersFinishedPercent;
        let a2 = a.stats.ordersFinishedTotal;
        let a3 = a.stats.ordersTotal;
        let b1 = b.stats.ordersFinishedPercent;
        let b2 = b.stats.ordersFinishedTotal;
        let b3 = b.stats.ordersTotal;
        switch (this.orderType) {
          case 'over':
            return a1 === b1 ? a2 === b2 ? b3 - a3 : b2 - a2 : b1 - a1
          default:
            return a2 === b2 ? a1 === b1 ? b3 - a3 : b1 - a1 : b2 - a2
        }
      });
    },
    exportStats(){
      this.$confirm('确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let startTime = this.startTime;
        let endTime = this.endTime;
        this.plugins.user.exportStatsOrderGovernmentBelong({startTime,endTime}).then((res) => {
          if(res.code == 0){
            this.plugins.modal.alert("导出任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
          }
        })
      })
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    init() {
      if (this.loading) return;
      this.loading = true;
      this.$root.$refs.navbar.init();
      this.plugins.user.call(async () => {
        let res = await this.plugins.user.init();
        if (res.code === 0) {
        }
        return res;
      }, async () => {
        if (this.access(this.$route.name)) return {code: 0};
        return this.env.xhrErrors.find((error) => error.code === 4);
      }).then((res) => {
        this.loading = false;
        this.$root.$refs.navbar.init();
        if (res.code === 0) {
          this.search();
        } else if (res.code === 2) {
          this.$root.$refs.navbar.login();
        } else {
          this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/home"));
        }
      });
    },
    exportExcel() {
      this.plugins.modal.toast("开始下载！", "success");
      const table = document.getElementById("exportTable-government-belong");
      const ws = XLSX.utils.table_to_sheet(table);

      // 设置单元格样式
      const range = XLSX.utils.decode_range(ws["!ref"]);
      for (let R = range.s.r; R <= range.e.r; ++R) {
        for (let C = range.s.c; C <= range.e.c; ++C) {
          const cellRef = XLSX.utils.encode_cell({ r: R, c: C });
          const cell = ws[cellRef];
          if (!cell) {
            continue;
          }
          cell.s = {
            alignment: {
              horizontal: "right",
              vertical: "center",
            },
          };
        }
      }
      // 自适应内容

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      XLSX.writeFile(wb, "办结率排名-自治区级及市区县职能部门.xlsx");
    },
  },
};
</script>

<style lang="scss">
.page-stats-order-government {
  overflow: hidden;
}

.page-stats-order-government__body {
  display: flex;
  flex-direction: column;

  .link {
    color: rgb(63, 108, 246) !important;
    &:hover {
      color: rgb(122, 153, 246);
      cursor: pointer;
    }
  }

  & > .row {
    flex: 0 0 auto;
    display: flex;
    width: 640px;

    & > .col {
      flex: 1 1 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 0 2px 2px 0;
      padding: 8px 9px;
      color: #333;
      font-size: 14px;
      line-height: 16px;
      text-align: center;
      background-color: #f6f6f6;

      & > .key {
        color: #1677ff;
      }
    }

    & > .link {
      color: rgb(63, 108, 246) !important;
      &:hover {
        color: rgb(122, 153, 246);
        cursor: pointer;
      }
    }

    & > .col--click {
      cursor: pointer;
    }

    & > .col--2em {
      flex: 0 0 auto;
      width: 2em;
    }

    & > .col--3em {
      flex: 0 0 auto;
      width: 3em;
    }

    & > .col--4em {
      flex: 0 0 auto;
      width: 4em;
    }

    &:first-child {
      & > .col {
        font-weight: bold;
      }
    }
  }
}
</style>
